#coding:utf-8
from app.models import BusinessSteps
from app.lib.MysqlPool import MysqlPool
import env_config
from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from app.lib.RedisPool import redisConn
import json
import requests
def business_mange(data,steps):
    flag = True
    for step in steps:
        if step.type == 'mysql':
            business_mysql(data,step)
        elif step.type =='redis':
            business_redis(data,step)
        elif step.type =='post':
            business_post(data,step)
        elif step.type == 'get':
            business_get(data, step)
        elif step.type == 'put':
            business_put(data, step)

    return flag


def business_mysql(data,step):
    flag = True
    temp = env_config.ENV_LIST.get(data.get('env_tools'))
    if temp is None:
        return False
    dbinfo=temp.get(step.var2)
    dbtool = MysqlPool(dbinfo.get('db_name'))
    data['db_name'] = dbinfo.get('table_name')
    sql=''
    try:
        sql = step.content % data
        print(sql)
        if step.var1 == 'select':
            result = dbtool.getOne(sql, None)

            if result and step.post is not None:
                for key in step.post.split(','):
                    data[key] = result.get(key)
                result=1
            else:
                result = 0
        elif step.var1 == 'delete':
            result = dbtool.delete(sql, None)
        elif step.var1 == 'update':
            result = dbtool.update(sql, None)
        elif step.var1 == 'insert':
            result = dbtool.insertOne(sql, None)
        data['log'] = data['log'] + sql + r' 操作成功 ' + str(result) + '条记录\n'
    except:
        flag = False
        data['log'] = data['log'] + step.var1 + '  '+ step.var3  + r' 操作失败\n'
    return flag


def business_redis(data,step):
    redisconf = env_config.ENV_LIST.get(data.get('env_tools')).get(step.var2)
    r = redisConn(redisconf)
    key = step.var4 % data
    if step.var1 == 'normal':
        value = step.content % data
        func = getattr(r, step.var3)
        print(func)
        func(key,value)
    elif step.var1 == 'single':
        func = getattr(r, step.var3)
        print(func)
        func(key)
    elif step.var1 == 'expire':
        r.expire(key,int(step.content))
    data['log'] = data['log']
    return True

def business_post(data,step):
    varibales = dict( env_config.ENV_LIST.get(data.get('env_tools')), **data )
    url =step.var1 % varibales
    headers = {}
    if step.var2:
        headers = json.loads(step.var2)
    params=''

    if step.content:
        params = step.content % varibales
    result = requests.post(url=url,
                          data=params, headers=headers)
    print(url, params, headers,result.content)
    return True

def business_put(data,step):
    varibales = dict(env_config.ENV_LIST.get(data.get('env_tools')), **data)
    url =step.var1 % varibales
    headers = {}
    if step.var2:
        headers = json.loads(step.var2)
        if type(headers) != 'dict':
            headers = {}
    params=''
    if step.content:
        params = step.content % varibales
    result = requests.put(url=url,
                          data=params, headers=headers)
    print(url, params, headers, result.content)
    return True

def business_get(data,step):
    varibales = dict(env_config.ENV_LIST.get(data.get('env_tools')), **data)
    url = step.var1 % varibales
    headers = {}
    if step.var2:
        headers = json.loads(step.var2)
        if type(headers) != 'dict':
            headers = {}
    result = requests.get(url=url, headers=headers)
    print(url,  headers, result.content)
    return True

if __name__ == '__main__':
    data = {}
    result = {
        'code': 0
    }
    data['idno'] = '411326'
    data['crfuid'] = 'bde4be99e4f15f2cab7ab1ffc48d4d31'
    data['env_tools'] = 'UAT'
    data['table_prefix'] = '1'

    engine = create_engine(r'sqlite:///E:\STU\python\lance-master\app.db')
    DBSession = sessionmaker(bind=engine)
    session = DBSession()

    steps = session.query(BusinessSteps).filter_by(business='deleteuser').order_by(
        BusinessSteps.sort.asc()).all()
    business_mange(data,steps)

